export const Tools = {
  dateFormat: function(date, fmt) {
    let ret;
    const opt = {
      "y+": date.getFullYear().toString(), // 年
      "M+": (date.getMonth() + 1).toString(), // 月
      "d+": date.getDate().toString(), // 日
      "H+": date.getHours().toString(), // 时
      "m+": date.getMinutes().toString(), // 分
      "s+": date.getSeconds().toString() // 秒
      // 有其他格式化字符需求可以继续添加，必须转化成字符串
    };
    for (let k in opt) {
      ret = new RegExp("(" + k + ")").exec(fmt);
      if (ret) {
        fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
      };
    };
    return fmt;
  },
  
  splitKeywords: function(line, keywords, maxLen) {
    if (!line) {
      return []
    }
    let len = line.length
    let splitList = [{value: "", match: false}]
    
    if (maxLen && len > maxLen) {
      line = line.substring(0, maxLen-1) + "..."
      len = line.length
    }
    
    for (let i = 0; i < len; i++) {
      let c = line[i]
      let slen = splitList.length
      let last = splitList[slen-1]
      let lastMatched = last.match
      let currMatched = keywords.indexOf(c) >= 0
      if (lastMatched && currMatched || !lastMatched && !currMatched) {
        last.value = last.value + c
        splitList[slen-1] = last
      } else {
        splitList.push({
          value: c,
          match: currMatched
        })
      }
    }
    return splitList
  },

  randomColorList: function(total) {
    if (!total || total <= 0) {
      return []
    }
    var WEEK_COLORS= [
      "#0091ff", "#dd3ee5", "#12e78c", "#fe8104", "#01C2F9", "#F4CB29",
      "#FD9E06", "#4B7CF3"
    ]
    var FIXED_COLORS = [
      "#FF3E96", "#98F5FF", "#9932CC", "#00E5EE", "#EE6A50", "#7FFFD4",
      "#C1FFC1", "#54FF9F", "#43CD80", "#6495ED", "#00FF7F", "#7B68EE",
      "#00FF00", "#00BFFF", "#87CEFA", "#C0FF3E", "#00CED1", "#FFEC8B",
      "#00FA9A", "#32CD32", "#FFFF00", "#FFD700", "#FFC1C1", "#DAA520",
      "#F4A460", "#FFA500", "#FF6347", "#BA55D3", "#9B30FF", "#BFEFFF"
    ]
    var colors = []
    
    if (total <= 8) {
      for(var i = 0; i < total; i++) {
        var item =  WEEK_COLORS[i];
        colors.push(item)
      }
    } else {
      for(var i = 0; i < total; i++){
        var index = Math.floor(Math.random() * FIXED_COLORS.length);
        var item =  FIXED_COLORS[index];
        colors.push(item)
        FIXED_COLORS.splice(index, 1)
      }
    }
    return colors
  }
}

function install(app) {
  app.config.globalProperties.$tools = Tools
}

export default {
  install
}